/**
 * 
 */
package com.lmm.db;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author leiming
 *
 */
public class PoolDB {
	private static final Logger log = LoggerFactory.getLogger(PoolDB.class);
	
	public static DataSource setupDataSource(String name) {
		 BasicDataSource dataSource = new BasicDataSource();
		 Properties dbProps = null;
		 try {
		  //Properties dbProps = getPoolInfo();
		  dbProps = getPoolMapInfo().get(name);
		 } catch (Exception e) {
			 log.error("加载数据库信息出错");
			 e.printStackTrace();
		 }
		  dbProps =( dbProps == null?new Properties():dbProps ); 
		  log.info("init db pool ");
		  dataSource.setUrl(dbProps.getProperty("url","jdbc:mysql://192.168.0.103:3306/ec_dev?characterEncoding=utf8&amp;zeroDateTimeBehavior=convertToNull"));
		  dataSource.setUsername(dbProps.getProperty("username","dev"));
		  dataSource.setPassword(dbProps.getProperty("password","dev"));
		  dataSource.setDriverClassName(dbProps.getProperty("driverClassName","com.mysql.jdbc.Driver"));
		  if(dbProps.getProperty("initialSize")!=null){
			  dataSource.setInitialSize(new Integer(dbProps.getProperty("initialSize","3")));
		  }
		  if(dbProps.getProperty("maxActive")!=null){
			  dataSource.setMaxActive(new Integer(dbProps.getProperty("maxActive","10")));
		  }
		  if(dbProps.getProperty("maxIdle")!=null){
			  dataSource.setMaxIdle(new Integer(dbProps.getProperty("maxIdle","20")));
		  }
		  if(dbProps.getProperty("minIdle")!=null)
			  dataSource.setMinIdle(new Integer(dbProps.getProperty("minIdle","10")));
		  if(dbProps.getProperty("maxWait")!=null)
			  dataSource.setMaxWait(new Long(dbProps.getProperty("maxWait","30000")));
		   
		  dataSource.setValidationQuery(dbProps.getProperty("validationQuery","select 1"));
		  if(dbProps.getProperty("testWhileIdle")!=null)
			  dataSource.setTestWhileIdle(new Boolean(dbProps.getProperty("testWhileIdle","false")));
		
		 return dataSource;

		 
    }
	
	/**
	  * 从META-INF/context.xml读取
	  */
	public static Properties getPoolInfo(){
		 Properties p = new Properties();
		 SAXReader read = new SAXReader();
			File file = null;
			try {
				URL url =PoolDB.class.getClassLoader().getResource("");
				//设置加载/context.xml
				try {
					file = new File(url.toURI());
				} catch (URISyntaxException e) {
					file = new File(url.getPath());
				}
				//跳到WEB-INF根文件文件夹下	，再跳到应用路径下
				file = file.getParentFile().getParentFile();	
				File cFile = new File(file,"META-INF/context.xml");
				//如果没有找到对应的配置文件
				if (!cFile.exists()) {
					throw new IllegalArgumentException(
							"META-INF/context.xml配置文件,请创建context.xml配置文件!");
				}
				Document document = read.read(cFile);
				Element root = document.getRootElement();
				
				Element context = root.element("Resource");
				log.debug("加载context.xml文件");
				for(Iterator it=context.attributeIterator();it.hasNext();){
						Attribute a = (Attribute) it.next();//
						String name = a.getName();
						String value = a.getValue();
		                p.put(name, value);
		                log.debug("属性名："+name+"   属性值："+value);
		            }
				
			} catch (DocumentException e) {
				log.error("加载context.xml文件出错");
				e.printStackTrace();
			}	
		return p;
	}
	 
	/**
	  * 从META-INF/context.xml读取
	  */
	@SuppressWarnings("unchecked")
	public static  Map<String,Properties> getPoolMapInfo() throws IllegalArgumentException{
		 Map<String,Properties> map = new HashMap<String, Properties>();
		 SAXReader read = new SAXReader();
			File file = null;
			try {
				URL url =PoolDB.class.getClassLoader().getResource("");
				//设置加载/context.xml
				try {
					file = new File(url.toURI());
				} catch (URISyntaxException e) {
					file = new File(url.getPath());
				}
				//跳到WEB-INF根文件文件夹下	，再跳到应用路径下
				file = file.getParentFile().getParentFile();	
				File cFile = new File(file,"META-INF/context.xml");
				//如果没有找到对应的配置文件
				if (!cFile.exists()) {
					throw new IllegalArgumentException(
							"META-INF/context.xml配置文件,请创建context.xml配置文件!");
				}
				Document document = read.read(cFile);
				Element root = document.getRootElement();
				
				List<Element> listContext = root.elements("Resource");
				log.debug("加载context.xml文件");
				for(Element e:listContext){
					Properties p = new Properties();
					String resName = e.attributeValue("name");
					if(resName==null){
						throw new RuntimeException("数据库配置文件里Resource没有配置name属性.");
					}
					map.put(resName, p);
					
					for(Iterator<?> it=e.attributeIterator();it.hasNext();){
							Attribute a = (Attribute) it.next();//
							String name = a.getName();
							String value = a.getValue();
			                p.put(name, value);
			                log.debug("属性名："+name+"   属性值："+value);
			            }// 2for
				}//1 for
				
				
			} catch (DocumentException e) {
				log.error("加载context.xml文件出错");
				//e.printStackTrace();
			}	
		return map;
	}
}
